<template>
  <div class="device-owner-layout">
    <AppSidebar
      :active-menu="activeMenu"
      ref="sidebarRef"
    >
      <template #menu-items>
        <el-menu-item index="/advertiser/dashboard">
          <el-icon><Monitor /></el-icon>
          <template #title>控制台</template>
        </el-menu-item>
        
        <el-menu-item index="/advertiser/ads">
          <el-icon><Picture /></el-icon>
          <template #title>我的广告</template>
        </el-menu-item>
        <el-menu-item index="/advertiser/negotiation">
          <el-icon><ChatLineRound /></el-icon>
          <template #title>协商列表</template>
        </el-menu-item>

        <el-menu-item index="/advertiser/management">
          <el-icon><Calendar /></el-icon>
          <template #title>排期管理</template>
        </el-menu-item>

        <el-menu-item index="/advertiser/billing">
          <el-icon><Wallet /></el-icon>
          <template #title>账单管理</template>
        </el-menu-item>

        <el-menu-item index="/advertiser/statistics">
          <el-icon><DataLine /></el-icon>
          <template #title>数据统计</template>
        </el-menu-item>
        
        <el-menu-item index="/advertiser/notification">
          <el-icon><Bell /></el-icon>
          <template #title>消息通知</template>
        </el-menu-item>
      </template>
    </AppSidebar>
    
    <div class="main-content" :class="{ 'expanded': sidebarRef?.isCollapsed }">
      <AppHeader
        :username="username"
        :user-avatar="userAvatar"
        :notification-count="notificationCount"
        @logout="handleLogout"
        @profile="handleProfile"
        @view-notifications="navigateToNotifications"
      />
         <!-- 添加一个测试按钮，直接测试跳转功能 -->
      <!-- <el-button 
        type="primary" 
        style="position: fixed; top: 10px; right: 100px; z-index: 1000;"
        @click="testNavigateToNotifications"
      >
        测试通知跳转
      </el-button> -->
      <div class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import { 
  Monitor, Picture, Calendar, DataLine, ChatLineRound, Wallet, Bell
} from '@element-plus/icons-vue';
import AppSidebar from '@/components/AppSidebar.vue';
import AppHeader from '@/components/AppHeader.vue';
import { useUserStore } from '@/stores/user';
import { getUserInfo } from '@/api/user';
import { getUnreadCount } from '@/api/notification';
import { onMounted } from 'vue';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const sidebarRef = ref(null);
let pollingTimer = null;
// 添加测试函数
// const testNavigateToNotifications = () => {
//   console.log('测试跳转到通知页面');
//   router.push('/notification');
// };

// 获取未读消息数量
const fetchUnreadCount = async () => {
  try {
    const res = await getUnreadCount();
    if (res.data.code === 200) {
      notificationCount.value = res.data.data || 0;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 开始轮询未读消息数量
const startPolling = () => {
  // 立即执行一次
  fetchUnreadCount();
  
  // 设置轮询，每分钟检查一次
  pollingTimer = setInterval(fetchUnreadCount, 60000);
};

// 导航到消息通知页面
const navigateToNotifications = () => {
  router.push('/advertiser/notification');
};

const username = computed(() => userStore.getUserInfo2().username || '未登录');
const userAvatar = computed(() => userStore.getUserInfo2()?.avatar || '');
const notificationCount = ref(0);
const activeMenu = computed(() => route.path);
const cachedViews = ref(['AdvertiserDashboard']);

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.clearToken();
    userStore.clearUserInfo();
    router.push('/login');
  }).catch(() => {});
};

const handleProfile = () => {
  router.push('/userinfo');
};

onMounted(() => {
  console.info("用户信息", userStore.getUserInfo2());
  // 启动轮询获取未读消息数量
  startPolling();
});

onBeforeUnmount(() => {
  // 组件销毁前清除定时器
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
});
</script>

<style scoped>
.device-owner-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: margin-left 0.3s;
}

.main-content.expanded {
  margin-left: -156px;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 消息通知徽章样式 */
.notification-badge {
  position: absolute;
  right: 20px;
}

/* 在折叠状态下的徽章位置调整 */
:deep(.el-menu--collapse) .notification-badge {
  right: 8px;
}
</style>